<script lang="ts" setup>
import { reactive, ref } from "vue"
import { ElMessage } from "element-plus"
import { useFormRules, useFormValid, useLoginState } from "../useLogin"
import { useUserStore } from "../../../store/modules/user"
import { getTenantIdByName, sendSmsCode } from "../../../api/login"
import { setTenantId } from "../../../utils/auth"
import router from "@/router/router"
import { PageEnum } from "../../../enums/pageEnum"
import { ErrorMessageMode } from "../../../utils/http/axios"
const { handleBackLogin } = useLoginState()
const userStore = useUserStore()
const loading = ref(false)
const smsLoading = ref(false)
const countdown = ref(0)
// 使用window对象来访问环境变量，避免TypeScript的import.meta错误
const tenantEnable = ref(window.__VITE_TENANT_ENABLE__ === "true")

const formRef = ref()
const { validForm } = useFormValid(formRef)
const { phoneRule, smsCodeRule, tenantNameRule } = useFormRules()

const formData = reactive({
  tenantName: "熵流力量", // 默认租户名
  phone: "",
  smsCode: "",
})

// 获取租户ID
async function getTenantId() {
  try {
    const res = await getTenantIdByName(formData.tenantName)
    setTenantId(res)
  } catch (error) {
    ElMessage.error("获取租户信息失败，请检查租户名称")
  }
}

// 发送验证码
async function handleSendSms() {
  try {
    if (!formData.phone) {
      ElMessage.warning("请输入手机号")
      return
    }

    smsLoading.value = true
    await sendSmsCode(formData.phone)

    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

    ElMessage.success("验证码已发送")
  } catch (error) {
    ElMessage.error("验证码发送失败")
  } finally {
    smsLoading.value = false
  }
}

// 登录处理
async function handleLogin() {
  try {
    // 表单验证
    const data = await validForm()
    if (!data) return

    // 获取租户ID
    await getTenantId()

    loading.value = true
    const userInfo = await userStore.login({
      // @ts-ignore
      mobile: formData.phone,
      smsCode: formData.smsCode,
      mode: ErrorMessageMode.MESSAGE,
    })

    if (userInfo) {
      ElMessage.success("登录成功")
      router.replace(PageEnum.BASE_HOME)
    }
  } catch (error) {
    console.error("登录失败:", error)
    ElMessage.error("登录失败，请检查手机号和验证码")
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="mobile-login-form">
    <el-form ref="formRef" :model="formData" label-position="top" @keyup.enter="handleLogin">
      <!-- 租户名输入 -->
      <el-form-item v-if="tenantEnable" prop="tenantName" :rules="tenantNameRule">
        <el-input v-model="formData.tenantName" placeholder="请输入租户名称" size="large" prefix-icon="el-icon-office-building" />
      </el-form-item>

      <!-- 手机号输入 -->
      <el-form-item prop="phone" :rules="phoneRule">
        <el-input v-model="formData.phone" placeholder="请输入手机号" size="large" prefix-icon="el-icon-mobile" />
      </el-form-item>

      <!-- 验证码输入 -->
      <el-form-item prop="smsCode" :rules="smsCodeRule">
        <div class="sms-code-input">
          <el-input v-model="formData.smsCode" placeholder="请输入验证码" size="large" prefix-icon="el-icon-message" />
          <el-button type="primary" :loading="smsLoading" :disabled="countdown > 0" @click="handleSendSms">
            {{ countdown > 0 ? `${countdown}秒后重试` : "获取验证码" }}
          </el-button>
        </div>
      </el-form-item>

      <!-- 登录按钮 -->
      <el-button type="primary" class="login-button" size="large" :loading="loading" @click="handleLogin"> 登录 </el-button>

      <!-- 返回账号登录 -->
      <div class="back-login">
        <el-button type="default" class="back-button" size="large" @click="handleBackLogin"> 返回账号登录 </el-button>
      </div>
    </el-form>
  </div>
</template>

<style lang="less" scoped>
.mobile-login-form {
  .sms-code-input {
    display: flex;

    .el-input {
      flex: 1;
      margin-right: 8px;
    }

    .el-button {
      width: 120px;
    }
  }

  .login-button {
    width: 100%;
    margin-bottom: 16px;
  }

  .back-login {
    margin-top: 16px;

    .back-button {
      width: 100%;
    }
  }
}
</style>
